import {
  ADDCHANNEL,
  DELCHANNEL,
  SETRESTCHANNELS,
  UPDATEACTIVECHANNELKEY,
  UPDATEARTICLE,
  UPDATECHANNELS
} from "@/store/actionTypes";
import {sortBy} from "lodash";

const initState = {
  userChannel: [], // 当前用户的频道数据
  restChannels: [], // 推荐频道的数据
  activeChannelKey: '', // 默认第一条数据选中
  channelArticles: {},  // {'channel_id': '文章列表数据'}
}

export const homeReducer = (state = initState, action) => {
  switch (action.type) {
    case UPDATECHANNELS:
      return {
        ...state,
        userChannel: action.payload,
        activeChannelKey: +action.payload[0]?.id,
      }
    case SETRESTCHANNELS:
      return {
        ...state,
        // 推荐频道数据更新上去
        restChannels: action.payload
      }
    case UPDATEACTIVECHANNELKEY:
      return {
        ...state,
        activeChannelKey: action.payload
      }
    case DELCHANNEL:
      return {
        ...state,
        userChannel: state.userChannel.filter(item => item.id !== action.payload.id),
        restChannels: sortBy([
          ...state.restChannels,
          action.payload
        ], 'id')
      }
    case ADDCHANNEL:
      return {
        ...state,
        userChannel: [
          ...state.userChannel,
          action.payload
        ],
        restChannels: state.restChannels.filter(item => item.id !== action.payload.id)
      }
    case UPDATEARTICLE:
      // {'频道id': {时间戳}}
      //  经过二次处理
      // 当前频道对应的列表数据
      // channelId, 数据
      const currentChannelArticle = state.channelArticles[action.payload.channel_id] || {
        pre_timestamp: null, // 获取数据的时间戳
        results: [] // 文章列表的数据
      }
      // 需求：
      // 1、时间戳每一个次接口请求，都要更新成接口返回的时间戳
      // 2、results数据，需要每次请求的时候，今天累加放到redux里面去
      const {channel_id, data: {pre_timestamp, results}} = action.payload
      return {
        ...state,
        channelArticles: {
          ...state.channelArticles,
          [channel_id]: {
            pre_timestamp, // 替换成最新的时间戳
            results: [
              //  不能直接替换
              //  直接替换了，原有的数据就没有了
              ...currentChannelArticle.results,
              ...results
            ]
          }
        }
      }
    default:
      return state
  }
}
